package com.xiangxiangjd.controller;

import com.alibaba.fastjson.JSONObject;
import com.xiangxiangjd.bean.TrUser;
import com.xiangxiangjd.config.FtpUtil;
import com.xiangxiangjd.config.token.JwtUtils;
import com.xiangxiangjd.controller.helper.$;
import com.xiangxiangjd.controller.model.ApiResultModel;
import com.xiangxiangjd.service.*;
import com.xiangxiangjd.utils.weChat.getOpenIdutil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.commons.fileupload.FileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 肖守凯
 * @date 2018-11-08
 */
@Slf4j
public abstract class BaseController {


  @Autowired private  FtpUtil ftpUtil;


  // 航材处置单号

  @Autowired ManagementDateNoService managementDateNoService;

  // 交接物品
  @Autowired HandoverGoodsService handoverGoodsService;

  // 归还
  @Autowired ReturnDateNoService returnDateNoService;

  // 交接物品
  @Autowired HandoverDateNoService handoverDateNoService;

  @Autowired ClaimConsumablesService claimConsumablesService;

  // 添加航材耗材 单号
  @Autowired DateNoService dateNoService;

  // 物品信息
  @Autowired GoodsService goodsService;
  // 申领批次号
  @Autowired ClaimDateNoService claimDateNoService;

  // 申领物品
  @Autowired ClaimGoodsService claimGoodsService;

  @Autowired protected JwtUtils jwtUtils;

  // 字典表翻译
  @Autowired SysDictService sysDictService;

  // 用户
  @Autowired TrUserService trUserService;
  // 角色
  @Autowired RoleService roleService;
  /** 单位 */
  @Autowired UnitService unitService;

  @Value("${jwt.config.ttl}")
  Long ttl;
  //
  //    @Value("${aliyun.oss.endpoint}")
  //    protected String endPoint = "";
  //
  //    @Value("${redisDS.group:dev}")
  //    String redisGroup = "";
  //
  //
  //    @Resource
  //    KeyValue keyValue;

  //    //存入 字符串 或者更新字符串 ES
  //    protected KV putESString(KV key) {
  //
  //        KV kv = keyValue.save(key);
  //
  //        return kv;
  //    }
  //
  //    // ES key 值 取出
  //    protected String getESString(String key) {
  //
  //        BoolQueryBuilder builder = QueryBuilders.boolQuery();
  //        builder.must(QueryBuilders.matchQuery("key", key));
  //        //构建查询
  //        NativeSearchQuery query = new NativeSearchQueryBuilder()
  //                .withQuery(builder)//查询条件
  //                .build();  //查询完毕
  //
  //        Page<KV> search = keyValue.search(query);
  //        List<KV> content = search.getContent();
  //        if (content.size() != 1) {
  //            System.out.println("发生了异常！");
  //        }
  //        return content.get(0).getValue();
  //    }
  //
  //    /**
  //     * ES 删除缓存
  //     */
  //    protected void deleteEs(String key) {
  //
  //        System.err.println("删除缓存成功");
  //        keyValue.deleteById(key);
  //
  //
  //    }

  // 获取当前用户
  //    public static AdminUser getUser() {
  //        return (AdminUser) SecurityUtils.getSubject().getPrincipal();
  //    }

  public  String uploadFile(MultipartFile file) throws IOException {

    System.out.println("ftp ****:"+ftpUtil.toString());

    // 获取上传文件流
    InputStream inputStream = file.getInputStream();

    // 获取上传文件名字
    String filename = file.getOriginalFilename();

    // 截取后缀
    String suffix = filename.substring(filename.lastIndexOf("."));

    // 使用UUID 拼接后缀，定义一个不重复的文件名
    String finaName = UUID.randomUUID() + suffix;

    FTPClient ftp = new FTPClient();
    try {
      int reply;
      ftp.connect(ftpUtil.getAddress(), ftpUtil.getPort()); // 链接FTP服务器
      ftp.login(ftpUtil.getUsername(), ftpUtil.getPassword()); // 登录
      reply = ftp.getReplyCode(); //
      // 判断是否链接的上  没链接上返回true
      if (!FTPReply.isPositiveCompletion(reply)) {
        // 断开链接
        ftp.disconnect();
        // 返回falese
        return null;
      }
      ftp.setFileType(FTPClient.BINARY_FILE_TYPE); // 文件类型 二进制的文件

      boolean b = ftp.makeDirectory(ftpUtil.getBasePath()); // 创建文件夹

      ftp.changeWorkingDirectory(ftpUtil.getBasePath()); // 改变目录
      ftp.enterLocalPassiveMode();
      ftp.storeFile(finaName, inputStream);
      inputStream.close();
      ftp.logout(); // 登录注销

    } catch (IOException e) {
      e.printStackTrace();
      return null;
    } finally {
      if (ftp.isConnected()) {
        try {
          // 断开链接
          ftp.disconnect();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

    return ftpUtil.getProtocol()+"://" +ftpUtil.getAddress() + ftpUtil.getAccessRouting() + finaName;
  }
  /**
   * XWPFDocument 转 MultipartFile（CommonsMultipartFile）
   *
   * @param document 文档对象
   * @param fileName 文件名
   * @return
   */
  protected   MultipartFile xwpfDocumentToCommonsMultipartFile(XWPFDocument document, String fileName) {
    //XWPFDocument转FileItem
   // org.apache.commons.fileupload.FileItemFactory factory = new DiskFileItemFactory(16, null);
    FileItemFactory factory=new DiskFileItemFactory(16,null);

    FileItem fileItem = factory.createItem("textField", "text/plain", true, fileName);
    try {
      OutputStream os = fileItem.getOutputStream();
      document.write(os);
      os.close();
      //FileItem转MultipartFile
      MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
      return multipartFile;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }



  /**
   * 获取OPEN ID方法
   *
   * @param jsCode
   * @return
   */
  protected String getOpenId(String jsCode) {
    getOpenIdutil getopenid = new getOpenIdutil();
    // 调用访问微信服务器工具方法，传入三个参数获取带有openid、session_key的json字符串
    String jsonId =
        getopenid.getopenid("wxa1ce8e939e3abe63", jsCode, "3900b7a8e71f5e0f145d1ba29e8f3c42");
    JSONObject jsonObject = JSONObject.parseObject(jsonId);
    // 从json字符串获取openid和session_key
    String openid = jsonObject.getString("openid");
    String session_key = jsonObject.getString("session_key");
    return openid;
  }

  /**
   * 获取当前请求
   *
   * @return request
   */
  protected HttpServletRequest getRequest() {
    return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
  }

  protected HttpSession getSession() {
    return getRequest().getSession();
  }

  /**
   * 获取当前响应
   *
   * @return response
   */
  protected HttpServletResponse getResponse() {
    return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
  }

  // 获取当前用户信息
  public TrUser getUserInfo() {

    String tokenHead = "Bearer ";
    HttpServletRequest request = getRequest();
    String token = request.getHeader("Authorization");
    Claims claims = jwtUtils.parseJwt(token.substring(tokenHead.length()));
    String username = claims.getId();
    return trUserService.getUser(username);
  }

  /**
   * 方法名称: renderText<br>
   * 描述：返回普通文本浏览器
   */
  protected void renderText(String text) {
    render(text, MediaType.TEXT_HTML_VALUE);
  }

  /**
   * 方法名称: renderJson<br>
   * 描述：返回JSON格式数据
   */
  protected void renderJson(String text) {
    render(text, MediaType.APPLICATION_JSON_UTF8_VALUE);
  }

  /**
   * 获取cookie
   *
   * @param cookieName
   * @return
   */
  protected String getCookie(String cookieName) {
    Cookie[] cookies = getRequest().getCookies();
    for (Cookie cookie : cookies) {
      if (cookieName.equals(cookie.getName())) {
        return cookie.getValue();
      }
    }

    return null;
  }

  /**
   * 设置 cookie
   *
   * @param cookieName
   * @param value
   * @param age
   */
  protected void setCookie(String cookieName, String value, int age) {
    Cookie cookie = new Cookie(cookieName, value);
    cookie.setMaxAge(age);
    getResponse().addCookie(cookie);
  }

  private void render(String text, String contentType) {
    HttpServletResponse response;
    try {

      response = getResponse();
      response.setContentType(contentType);

      response.getWriter().write(text);
      response.getWriter().flush();
    } catch (IOException e) {
      throw new IllegalStateException(e);
    }
  }

  /**
   * request内参数 转map
   *
   * @return
   */
  protected Map<String, Object> convertDataMap() {
    Map<String, String[]> properties = getRequest().getParameterMap();
    Map<String, Object> returnMap = new HashMap<String, Object>();
    Iterator<?> entries = properties.entrySet().iterator();
    Map.Entry<?, ?> entry;
    String name = "";
    String value = "";
    while (entries.hasNext()) {
      entry = (Map.Entry<?, ?>) entries.next();
      name = (String) entry.getKey();
      Object valueObj = entry.getValue();
      if (null == valueObj) {
        value = "";
      } else if (valueObj instanceof String[]) {
        String[] values = (String[]) valueObj;
        for (int i = 0; i < values.length; i++) {
          value = values[i] + ",";
        }
        value = value.substring(0, value.length() - 1);
      } else {
        value = valueObj.toString();
      }
      returnMap.put(name, value);
    }
    return returnMap;
  }

  /**
   * 对象转数组
   *
   * @param obj
   * @return
   */
  protected static byte[] objectToByteArray(Object obj) {
    byte[] bytes = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
      ObjectOutputStream oos = new ObjectOutputStream(bos);
      oos.writeObject(obj);
      oos.flush();
      bytes = bos.toByteArray();
      oos.close();
      bos.close();
    } catch (IOException ex) {
      ex.printStackTrace();
    }
    return bytes;
  }

  /**
   * 数组转对象
   *
   * @param bytes
   * @return
   */
  protected static Object byteArrToObject(byte[] bytes) {
    Object object = null;
    try {
      ByteArrayInputStream byteArrayInputStream =
          new ByteArrayInputStream(bytes); // 创建ByteArrayInputStream对象
      ObjectInputStream objectInputStream =
          new ObjectInputStream(byteArrayInputStream); // 创建ObjectInputStream对象
      object = objectInputStream.readObject(); // 从objectInputStream流中读取一个对象
      byteArrayInputStream.close(); // 关闭输入流
      objectInputStream.close(); // 关闭输入流
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }

    return object; // 返回对象
  }

  public static String getIPAddress(HttpServletRequest request) {
    String ip = null;

    // X-Forwarded-For：Squid 服务代理
    String ipAddresses = request.getHeader("X-Forwarded-For");

    if (ipAddresses == null
        || ipAddresses.length() == 0
        || "unknown".equalsIgnoreCase(ipAddresses)) {
      // Proxy-Client-IP：apache 服务代理
      ipAddresses = request.getHeader("Proxy-Client-IP");
    }

    if (ipAddresses == null
        || ipAddresses.length() == 0
        || "unknown".equalsIgnoreCase(ipAddresses)) {
      // WL-Proxy-Client-IP：weblogic 服务代理
      ipAddresses = request.getHeader("WL-Proxy-Client-IP");
    }

    if (ipAddresses == null
        || ipAddresses.length() == 0
        || "unknown".equalsIgnoreCase(ipAddresses)) {
      // HTTP_CLIENT_IP：有些代理服务器
      ipAddresses = request.getHeader("HTTP_CLIENT_IP");
    }

    if (ipAddresses == null
        || ipAddresses.length() == 0
        || "unknown".equalsIgnoreCase(ipAddresses)) {
      // X-Real-IP：nginx服务代理
      ipAddresses = request.getHeader("X-Real-IP");
    }

    // 有些网络通过多层代理，那么获取到的ip就会有多个，一般都是通过逗号（,）分割开来，并且第一个ip为客户端的真实IP
    if (ipAddresses != null && ipAddresses.length() != 0) {
      ip = ipAddresses.split(",")[0];
    }

    // 还是不能获取到，最后再通过request.getRemoteAddr();获取
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
      ip = request.getRemoteAddr();
    }
    return ip;
  }

  /**
   * 程序异常 因为有切面日志的原因如果控制层报错 则会打印两次日志 一次是请求的切点 一次是 本异常类的切点
   *
   * @param e
   * @return
   */
  @ExceptionHandler(Exception.class)
  @ResponseBody
  public ApiResultModel<Object> serverException(Exception e) {
    //  logger.error(e.getStackTrace());
    if (e instanceof AuthorizationException) {
      return $.error("无权限进行此操作");
    } else if (e instanceof AccessDeniedException) {
      return $.error(501, "无权限进行此操作");
    }
    //        System.out.println("异常处理了");
    //            return  $.error(e.getMessage());
    e.printStackTrace(System.out);
    return $.error(e.getMessage());
  }

  /**
   * - 时间戳转换为日期格式
   *
   * <p>肖守凯
   *
   * @return
   */
  protected static String StringToDate(String time) {

    Date d = new Date(Long.valueOf(time));

    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    return sf.format(d);
  }

  public static void main(String[] args) {

    ArrayList<Object> objects = new ArrayList<>();

    objects.isEmpty();
  }


  protected List<String> getDifferentPartsOfTheList(List mysqlGoodsId,List xlsxGoodsId) {

    Collection exists = new ArrayList(mysqlGoodsId);
    Collection notexists = new ArrayList(mysqlGoodsId);
    exists.removeAll(xlsxGoodsId);
    System.out.println("_second中不存在于_set中的：" + exists);
    notexists.removeAll(exists);
    System.out.println("_second中存在于_set中的：" + notexists);

    return new ArrayList(notexists);

  }



}
